package com.jackeysun.common.text

import android.graphics.Color
import android.graphics.Typeface
import android.text.Editable
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.AbsoluteSizeSpan
import android.text.style.BackgroundColorSpan
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.widget.TextView
import androidx.core.text.inSpans

/**
 *   Created by sunxunchao on 2021/12/3.
 */

object StringExt {
    val Span = SpannableStringBuilder()
}

fun SpannableStringBuilder.addSection(
    section: CharSequence
): SpannableStringBuilder = this.append(section)

fun SpannableStringBuilder.addStyleSection(
    section: CharSequence,
    textColor: Int = Color.GRAY,
    textSize: Int = 12,
    backgroundColor: Int = Color.WHITE,
    textStyle: Int = Typeface.NORMAL
): SpannableStringBuilder {
    return this.addStyleSection(
        section,
        ForegroundColorSpan(textColor),
        BackgroundColorSpan(backgroundColor),
        AbsoluteSizeSpan(textSize, true),
        StyleSpan(textStyle),
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
    )
}

//fun SpannableStringBuilder.addStyleSection(
//    section: String,
//    vararg span: Any
//): SpannableStringBuilder =
//    this.addStyleSection(section, span, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

/**
 * 添加字体片段
 * @param section 要添加的文字
 * @param span
 * @param flag    可以是
 *                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE 不包含section前后文字，最常用
 *                Spanned.SPAN_INCLUSIVE_EXCLUSIVE 包含section前面文字
 *                Spanned.SPAN_EXCLUSIVE_INCLUSIVE 包含section后面文字
 *                Spanned.SPAN_INCLUSIVE_INCLUSIVE 包含section前后文字
 *                ……
 * @return SpanBuilder
 */
fun SpannableStringBuilder.addStyleSection(
    section: CharSequence,
    vararg span: Any,
    flag: Int = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
): SpannableStringBuilder {
    val start: Int = this.length
    this.append(section)
    val end: Int = this.length
    span.map {
        this.setSpan(it, start, end, flag)
    }
    return this
}

fun SpannableStringBuilder.inStyleSection(
    vararg span: Any,
): SpannableStringBuilder {
    span.map {
//        this.setSpan(it, start, end, flag)
        this.inSpans(span) {

        }
    }
    return this
}

inline fun <reified V : TextView> SpannableStringBuilder.into(textView: V) {
    textView.text = this
    this.clear()
}


fun TextView.getEditable(): Editable? {
    val text: CharSequence = this.text ?: return null
    // This can only happen during construction.
    if (text is Editable) {
        return this.text as Editable
    }
    this.setText(text, TextView.BufferType.EDITABLE)
    return this.text as Editable
}